package top.fzqblog.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.fzqblog.exception.BizException;
import top.fzqblog.model.Prize;
import top.fzqblog.model.User;
import top.fzqblog.model.UserPrize;

import java.util.Date;

/**
 * Created by 抽离 on 2017/9/4 0004.
 */
@Service
public class UserPrizeService {

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addUserPrize(User user, Integer prizeId) throws BizException{
        Prize prize = new Prize().selectById(prizeId);
        if(user.getUserStatus() == 0 || prize == null || prize.getStatus() == 0){
            throw new BizException("参数错误！");
        }else if(user.getCredits() < prize.getCredits()){
            throw new BizException("积分不足！");
        }
        else{
            user.setCredits(user.getCredits() - prize.getCredits());
            user.updateById();
            UserPrize userPrize = new UserPrize();
            userPrize.setCreateTime(new Date());
            userPrize.setUserId(user.getUserId());
            userPrize.setUserName(user.getUserName());
            userPrize.setTel(user.getTel());
            userPrize.setPrizeId(prizeId);
            userPrize.setPrizeImgurl(prize.getPrizeImg());
            userPrize.setPrizeName(prize.getPrizeName());
            userPrize.insert();
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void ConfirmDui(Integer id) throws BizException{
        UserPrize userPrize = new UserPrize().selectById(id);
        if(userPrize == null){
            throw new BizException("参数错误！");
        }else if(userPrize.getStatus() == 1){
            throw new BizException("已兑换，不能重复兑换");
        }
        else{
            userPrize.setStatus(1);
            userPrize.updateById();
        }
    }
}
